// ignore_for_file: use_build_context_synchronously

import 'package:client_flutter_door/bean/cabinet.dart';
import 'package:client_flutter_door/bean/cqxx.dart';
import 'package:client_flutter_door/http/box.dart';
import 'package:client_flutter_door/http/door.dart';
import 'package:client_flutter_door/model/door_model.dart';
import 'package:client_flutter_door/utils/info.dart';
import 'package:client_flutter_door/vars.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:collection/collection.dart';
import 'package:provider/provider.dart';

class Netframework {
  static int count = 0;
  static getAlcohol(List<Cabinet> boxs) async {
    // print("开始获取测酒数目***");
    var request =
        http.Request('GET', Uri.parse('${Vars.netframeworkUrl}/alcohol.ashx'));
    http.StreamedResponse response = await request.send();
    if (response.statusCode == 200) {
      final result = await response.stream.bytesToString();
      final intResult = int.parse(result);

      // print("获取测酒数目:${intResult}");
      if (count == 0) {
        count = intResult;
        return;
      }
      final disCount = intResult - count;
      count = intResult;
      //一般是新增的：出乘、退乘
      if (disCount != 0) {
        // print('获取最新的一条数据：');
        var request = http.Request(
            'GET',
            Uri.parse(
                '${Vars.netframeworkUrl}/alcohol.ashx?action=num&num=${disCount.abs()}'));
        http.StreamedResponse response = await request.send();
        if (response.statusCode == 200) {
          final result = await response.stream.bytesToString();
          List<Cqxx> data = cqxxFromJson(result);
          // print('获取的数据$data');
          // print(data.length);
          // print('data[0].qdlb = ${data[0].qdlb}');
          // print('row.jl = ${data[0].jl}');
          // print(data.toString());
          final userczhs =
              Vars.navigatorKey.currentContext!.read<DoorModel>().userczhs;
          for (int i = 0; i < data.length; i++) {
            Cqxx row = data[i];
            if (row.cjjg != '正常') {
              Info.snackbarWithoutContext('${row.name}测酒结果异常（${row.cjjg}）');
              return;
            }

            RegExp exp = RegExp(r'[0-9]{4}$');
            if (row.jl == null || row.jl == '' || !exp.hasMatch(row.jl!)) {
              Info.snackbarWithoutContext('${row.name}没有输入车组号');
              return;
            }

            if (row.qdlb != null) {
              if (boxs.isNotEmpty) {
                // print('boxs.lengthboxs.length = ${boxs.length}');
                // if (row.qdlb == "退乘") {
                //添加到记录并修改柜门状态czh=row.jl
                final len = row.jl?.length ?? 0;

                if (len > 3) {
                  //测酒的车组号
                  String rowCzh = row.jl!.substring(len - 4);
                  bool isCh400af = row.jl!.toLowerCase().contains('s');
                  
                  final box = boxs.firstWhereOrNull((r) {
                    if (isCh400af) {
                      return (r.czh == rowCzh) && r.is400AF;
                    } else {
                      return (r.czh == rowCzh) && !r.is400AF;
                    }
                  });
                  if (isCh400af) {
                    rowCzh = 'S$rowCzh';
                  }
                  //开门
                  if (box != null) {
                    if (userczhs.isNotEmpty) {
                      //出乘计划是否包含车组
                      if (userczhs.containsKey(rowCzh)) {
                        //包含车组
                        final users = userczhs[rowCzh];
                        if (users == null ||
                            users == '' ||
                            row.name == null ||
                            row.name == '') {
                          if (row.name == null || row.name == '') {
                            Info.snackbarWithoutContext('$rowCzh 测酒数据没有姓名不开门');
                            return;
                          }
                          Info.snackbarWithoutContext('$rowCzh 出乘交路没有姓名不开门');
                          return;
                        }

                        //多个人
                        if (users.contains('/')) {
                          final listUsers = users.split('/');
                          final findIndex = listUsers.indexOf(row.name!);
                          if (findIndex == -1) {
                            Info.snackbarWithoutContext(
                                '$rowCzh 出乘交路的姓名$users没有匹配到测酒姓名${row.name}不开门');
                            return;
                          } else {
                            //findIndex==0+出乘情况开门
                            if (findIndex == 0 && row.qdlb == '退乘') {
                              Info.snackbarWithoutContext(
                                  '$rowCzh 换乘情况$users不开门');
                              return;
                            }
                            if (findIndex == listUsers.length - 1 &&
                                row.qdlb == '出乘') {
                              Info.snackbarWithoutContext(
                                  '$rowCzh 换乘情况$users不开门');
                              return;
                            }
                          }
                        } else {
                          //开门
                          if (!users.contains(row.name!)) {
                            Info.snackbarWithoutContext(
                                '$rowCzh 出乘交路的姓名$users没有匹配到测酒姓名${row.name}不开门');
                            return;
                          }
                        }
                        await Door.open(box.BlId);
                      } else {
                        Info.snackbarWithoutContext('不开门');
                      }
                    } else {
                      Info.snackbarWithoutContext('右下角上传计划开启自动开门和过滤换乘情况不开门');
                      // return;
                    }
                    //匹配车组号
                    //匹配姓名是否存在/

                    Info.snackbarWithoutContext('${box.id}号柜门已打开');

                    // 测酒出乘的开门+标记为空
                    // 测酒退乘的开门+标记为占用
                    var isOccupied = false;
                    if (row.qdlb == '退乘') {
                      isOccupied = true;
                    }

                    await Box.setBox(box.id, box.czh, isOccupied, false);
                    // Provider.of<DoorModel>(context, listen: false)
                    //     .setBoxOccupied(box.id, isOccupied);
                    if (Vars.navigatorKey.currentContext != null) {
                      debugPrint('Vars.navigatorKey.currentContext != null');
                      Vars.navigatorKey.currentContext!
                          .read<DoorModel>()
                          .setBoxOccupied(box.id, isOccupied);
                    } else {
                      debugPrint('Vars.navigatorKey.currentContext == null');
                    }

                    // Provider.of<DoorModel>(Vars.navigatorKey.currentContext!,
                    //         listen: false)
                    //     .setBoxOccupied(box.id, isOccupied);
                    // await Door.open(box.box.BlId);
                  } else {
                    Info.snackbarWithoutContext(
                        '${row.name} ${row.qdlb} 没有匹配到车组号');
                  }
                }
              } else {
                print('00000000000000');
              }
            }
          }
        } else {
          print('获取增加的数据失败');
        }
      }
    } else {
      print('获取测酒数目');
    }
  }
}
